package com.mk.legoscans2.data;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CachingFavoritesRepository implements FavoritesRepository {

	FavoritesRepository _inner;
	
	private List<String> _getFavoritesCache;
	private Map<String, Boolean> _isFavoriteCache;
	
	public CachingFavoritesRepository(FavoritesRepository inner){
		_inner = inner;
		_isFavoriteCache = new HashMap<String, Boolean>();
	}
	
	public List<String> getFavorites() {
		if(_getFavoritesCache == null)
			_getFavoritesCache = _inner.getFavorites();
			
		return _getFavoritesCache;
	}

	public boolean toggleFavorite(String scanId) {
		invalidateCache();
		return _inner.toggleFavorite(scanId);
	}

	public boolean isFavorite(String scanId) {
		if(!_isFavoriteCache.containsKey(scanId))
			_isFavoriteCache.put(scanId, _inner.isFavorite(scanId));
		
		return _isFavoriteCache.get(scanId);
	}

	private void invalidateCache(){
		_getFavoritesCache = null;
		_isFavoriteCache.clear();
	}
}
